package com.jfcloud.common.aspect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;

public class BaseAspect {
	private static final Logger logger = LoggerFactory.getLogger(BaseAspect.class);
	
	public static final String request = "request";
	public static final String response = "response";
	public static final String requestBody = "requestBody";
	
	protected Map<String,Object> analysisArgs(Object[] args,Method method) {
		Map<String,Object> argMap = new HashMap<String,Object>();
		Annotation[][] annotations = method.getParameterAnnotations();
		for(int i=0;i<args.length;i++){
			if (args[i] instanceof HttpServletRequest) {  
				argMap.put(request,args[i]);
			}else if(args[i] instanceof HttpServletResponse){
				argMap.put(response,args[i]);
			}else if(isRequestBody(i,annotations)){
				argMap.put(requestBody,args[i]);
			}else{
//				logger.info("unkown arg : "+"index:"+i+" object:"+args[i]);
			}
		}
//		logger.info("args:"+args);
		return argMap;
	}
	
	/**
	 * 判断是否是requestBody
	 * @param index
	 * @param parameterAnnotations
	 * @return
	 */
	private boolean isRequestBody(int index,Annotation[][] parameterAnnotations){
		 for(int j=0;j<parameterAnnotations.length;j++)
         {
             int length = parameterAnnotations[j].length;
             if(length == 0)   //如果为0，则表示没有为该参数添加注释
             {
                 continue;
             }
             else
             {
                 for(int k=0;k<length;k++)
                 {
                     //获得参数注释
                     Annotation pa = parameterAnnotations[j][k];
                     if(j==index&&pa instanceof RequestBody){
                    	 return true;
                     }
                 }
             }
         }
		 return false;
	}
	
	
}